﻿/*
FTPFactory.cs
Better view with tab space=4

Written by Jaimon Mathew (jaimonmathew@rediffmail.com)
Rolander,Dan (Dan.Rolander@marriott.com) has modified the 
download
method to cope with file name with path information. He also 
provided
the XML comments so that the library provides Intellisense 
descriptions.

use the following line to compile
csc /target:library /out:FTPLib.dll /r:System.DLL FTPFactory.cs
*/

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;
using System.Linq;

namespace FonShare.Classes.FTP
{
    /// <summary>
    /// FTPFactory to create FTP connection to server.
    /// </summary>
    /// <author>spesme</author>
    /// <since>26/06/2009</since>
    public class FS_FTPFactory
    {
        private static int BLOCK_SIZE = 512;
        private static int DEFAULT_PORT = 21;
        Encoding ASCII = Encoding.ASCII;
        private static string SPACE = " ";
        private static string OPEN_BRACKET = "(";
        private static string CLOSE_BRACKET = ")";


        /// <summary>
        /// List of FTP Commands.
        /// </summary>
        /// <author>spesme</author>
        /// <since>26/06/2009</since>
        public static class FTPCommand
        {
            public const string LIST = "LIST";
            // Name List of remote directory.
            public const string NLST = "NLST";
        }

        public string Host; 
        public string ThePath;
        public string User; 
        public string Password;
        public int Port;

        public int ReturnValue;
        public string Reply;

        private string message;
        private int bytes;
        private Socket clientSocket;

        private Boolean debug = false;
        private Boolean logined = false;
        
        Byte[] buffer = new Byte[BLOCK_SIZE];


        /// <summary>
        /// Initializes a new instance of the <see cref="FS_FTPFactory"/> class.
        /// </summary>
        /// <param name="p_host">The p_host.</param>
        /// <param name="p_path">The p_path.</param>
        /// <param name="p_user">The p_user.</param>
        /// <param name="p_password">The p_password.</param>
        /// <author>spesme</author>
        /// <since>23/06/2009</since>
        public FS_FTPFactory(string p_host, string p_path, string p_user, string p_password)
        {
            Host = p_host;
            ThePath = p_path;
            User = p_user;
            Password = p_password;
            Port = DEFAULT_PORT;
        }

        /// <summary>
        /// Determines whether this instance is login.
        /// </summary>
        /// <author>spesme</author>
        /// <since>26/06/2009</since>
        private void isLogin()
        {
            if (!logined)
            {
                login();
            }
        }

        /// <summary>
        /// Return a string array containing the remote directory's file list.
        /// </summary>
        /// <param name="mask">The mask.</param>
        /// <returns></returns>
        public string[] getFileList(string mask)
        {
            isLogin();
            Socket cSocket = createDataSocket();
            sendCommand(FTPCommand.NLST + SPACE + mask);
            if (!(ReturnValue == 150 || ReturnValue == 125))
            {
                throw new IOException(Reply.Substring(4));
            }

            message = "";

            while (true)
            {
                int bytes = cSocket.Receive(buffer, buffer.Length, 0);
                message += ASCII.GetString(buffer, 0, bytes);

                if (bytes < buffer.Length)
                {
                    break;
                }
            }

            char[] seperator = { '\n' };
            string[] mess = message.Split(seperator);

            cSocket.Close();

            readReply();

            if (ReturnValue != 226)
            {
                throw new IOException(Reply.Substring(4));
            }
            return mess;
        }

        /// <summary>
        /// Gets the string file list.
        /// </summary>
        /// <param name="p_mask">The p_mask.</param>
        /// <returns>A list of files as string.</returns>
        /// <author>spesme</author>
        /// <since>26/06/2009</since>
        public List<String> GetSimpleFileList(string p_mask)
        {
            List<FS_FTPFile> filesList = GetEnhancedFileList(p_mask);
            return filesList.Select(record => record.Name + " (" + record.DisplaySize() + ")").ToList();
        }

        /// <summary>
        /// Gets the enhanced file list.
        /// </summary>
        /// <param name="p_mask">The mask.</param>
        /// <returns>A List of files.</returns>
        /// <author>spesme</author>
        /// <since>26/06/2009</since>
        public List<FS_FTPFile> GetEnhancedFileList(string p_mask)
        {
            List<FS_FTPFile> result = new List<FS_FTPFile>();
            isLogin();
            Socket cSocket = createDataSocket();
            // Send LIST to get information about files in current directory. 
            sendCommand(FTPCommand.LIST + SPACE + p_mask);
            if (!(ReturnValue == 150 || ReturnValue == 125))
            {
                throw new IOException(Reply.Substring(4));
            }

            message = "";

            // Read response from FTP Server. A list of files equivalent to that one.
            //     -rw-r--r-- 1 ftp ftp            470 Jan 15  2009 IRON.lnk                              
			//     drwxr-xr-x 1 ftp ftp              0 Jun 24 14:53 MyFolder                        
			//     -rw-r--r-- 1 ftp ftp            694 Jan 12  2009 Notepad++.lnk                 
            //     -rwxr-xr-x 1 ftp ftp        2038658 Jan 12  2009 npp.5.1.1.Installer.exe
            while (true)
            {
                int bytes = cSocket.Receive(buffer, buffer.Length, 0);
                message += ASCII.GetString(buffer, 0, bytes);
                if (bytes < buffer.Length)
                {
                    break;
                }
            }

            char[] separator = { '\n' };
            string[] filesList = message.Split(separator);

            cSocket.Close();

            readReply();

            if (ReturnValue != 226)
            {
                throw new IOException(Reply.Substring(4));
            }
            result = FS_FTPFileManager.GetFiles(filesList, p_mask);
            List<FS_FTPFile> subfolderFilesList = new List<FS_FTPFile>();
            foreach (FS_FTPFile currentDirectory in result.Where(record => record.IsDirectory))
            {
                subfolderFilesList.AddRange(GetEnhancedFileList(currentDirectory.Name));
            }
            result.AddRange(subfolderFilesList);
            return result;
        }

        /// <summary>
        /// Gets the size of the file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public long getFileSize(string fileName)
        {
            isLogin();
            sendCommand("SIZE " + fileName);
            long size = 0;

            if (ReturnValue == 213)
            {
                size = Int64.Parse(Reply.Substring(4));
            }
            else
            {
                throw new IOException(Reply.Substring(4));
            }
            return size;
        }


        /// <summary>
        /// Login to the remote server.
        /// </summary>
        /// <author>spesme</author>
        /// <since>26/06/2009</since>
        public void login()
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ep = new IPEndPoint(Dns.Resolve(Host).AddressList[0], Port);

            try
            {
                clientSocket.Connect(ep);
            }
            catch (Exception)
            {
                throw new IOException("Couldn't connect to remote server");
            }
            Thread.Sleep(1000);
            readReply();
            if (ReturnValue != 220)
            {
                close();
                throw new IOException(Reply.Substring(4));
            }
            if (debug)
                Console.WriteLine("USER " + User);

            sendCommand("USER " + User);

            if (!(ReturnValue == 331 || ReturnValue == 230))
            {
                cleanup();
                throw new IOException(Reply.Substring(4));
            }

            if (ReturnValue != 230)
            {
                if (debug)
                    Console.WriteLine("PASS xxx");

                sendCommand("PASS " + Password);
                if (!(ReturnValue == 230 || ReturnValue == 202))
                {
                    cleanup();
                    throw new IOException(Reply.Substring(4));
                }
            }

            logined = true;
            Console.WriteLine("Connected to " + Host);

            chdir(ThePath);

        }

        /// <summary>
        /// If the value of mode is true, set binary mode for downloads.
        /// Else, set Ascii mode.
        /// </summary>
        /// <param name="mode">if set to <c>true</c> [mode].</param>
        public void setBinaryMode(Boolean mode)
        {
            if (mode)
            {
                sendCommand("TYPE I");
            }
            else
            {
                sendCommand("TYPE A");
            }
            if (ReturnValue != 200)
            {
                throw new IOException(Reply.Substring(4));
            }
        }

        /// Download a file to the Assembly's local directory,
        /// keeping the same file name.
        public void download(string remFileName)
        {
            download(remFileName, "", false);
        }

        /// Download a remote file to the Assembly's local directory,
        /// keeping the same file name, and set the resume flag.
        public void download(string remFileName, Boolean resume)
        {
            download(remFileName, "", resume);
        }

        /// Download a remote file to a local file name which can include
        /// a path. The local file name will be created or overwritten,
        /// but the path must exist.
        public void download(string remFileName, string locFileName)
        {
            download(remFileName, locFileName, false);
        }

        /// Download a remote file to a local file name which can include
        /// a path, and set the resume flag. The local file name will be
        /// created or overwritten, but the path must exist.
        public void download(string remFileName, string locFileName, Boolean resume)
        {
            if (!logined)
            {
                login();
            }

            setBinaryMode(true);

            Console.WriteLine("Downloading file " + remFileName + " from " + Host + "/" + ThePath);

            if (locFileName.Equals(""))
            {
                locFileName = remFileName;
            }

            if (!File.Exists(locFileName))
            {
                Stream st = File.Create(locFileName);
                st.Close();
            }

            FileStream output = new FileStream(locFileName, FileMode.Open);

            Socket cSocket = createDataSocket();

            long offset = 0;

            if (resume)
            {

                offset = output.Length;

                if (offset > 0)
                {
                    sendCommand("REST " + offset);
                    if (ReturnValue != 350)
                    {
                        //throw new IOException(reply.Substring(4));
                        //Some servers may not support resuming.
                        offset = 0;
                    }
                }

                if (offset > 0)
                {
                    if (debug)
                    {
                        Console.WriteLine("seeking to " + offset);
                    }
                    long npos = output.Seek(offset, SeekOrigin.Begin);
                    Console.WriteLine("new pos=" + npos);
                }
            }

            sendCommand("RETR " + remFileName);

            if (!(ReturnValue == 150 || ReturnValue == 125))
            {
                throw new IOException(Reply.Substring(4));
            }

            while (true)
            {

                bytes = cSocket.Receive(buffer, buffer.Length, 0);
                output.Write(buffer, 0, bytes);

                if (bytes <= 0)
                {
                    break;
                }
            }

            output.Close();
            if (cSocket.Connected)
            {
                cSocket.Close();
            }

            Console.WriteLine("");

            readReply();

            if (!(ReturnValue == 226 || ReturnValue == 250))
            {
                throw new IOException(Reply.Substring(4));
            }

        }

        /// <summary>
        /// Uploads the specified file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        public void upload(string fileName)
        {
            upload(fileName, false);
        }

        /// <summary>
        /// Upload a file and set the resume flag.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="resume">if set to <c>true</c> [resume].</param>
        public void upload(string fileName, Boolean resume)
        {
            isLogin();
            Socket cSocket = createDataSocket();
            long offset = 0;
            if (resume)
            {
                try
                {
                    setBinaryMode(true);
                    offset = getFileSize(fileName);
                }
                catch (Exception)
                {
                    offset = 0;
                }
            }
            if (offset > 0)
            {
                sendCommand("REST " + offset);
                if (ReturnValue != 350)
                {
                    //throw new IOException(reply.Substring(4));
                    //Remote server may not support resuming.
                    offset = 0;
                }
            }
            sendCommand("STOR " + Path.GetFileName(fileName));
            if (!(ReturnValue == 125 || ReturnValue == 150))
            {
                throw new IOException(Reply.Substring(4));
            }
            // open input stream to read source file
            FileStream input = new FileStream(fileName, FileMode.Open);
            if (offset != 0)
            {
                if (debug)
                {
                    Console.WriteLine("seeking to " + offset);
                }
                input.Seek(offset, SeekOrigin.Begin);
            }

            Console.WriteLine("Uploading file " + fileName + " to " + ThePath);

            while ((bytes = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                cSocket.Send(buffer, bytes, 0);
            }
            input.Close();
            Console.WriteLine("");
            if (cSocket.Connected)
            {
                cSocket.Close();
            }
            readReply();
            if (!(ReturnValue == 226 || ReturnValue == 250))
            {
                throw new IOException(Reply.Substring(4));
            }
        }

        /// <summary>
        /// Delete a file from the remote FTP server.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        public void deleteRemoteFile(string fileName)
        {
            isLogin();
            sendCommand("DELE " + fileName);
            if (ReturnValue != 250)
            {
                throw new IOException(Reply.Substring(4));
            }
        }

        /// <summary>
        /// Rename a file on the remote FTP server.
        /// </summary>
        /// <param name="oldFileName">Old name of the file.</param>
        /// <param name="newFileName">New name of the file.</param>
        public void renameRemoteFile(string oldFileName, string newFileName)
        {
            isLogin();
            sendCommand("RNFR " + oldFileName);
            if (ReturnValue != 350)
            {
                throw new IOException(Reply.Substring(4));
            }
            //  known problem
            //  rnto will not take care of existing file.
            //  i.e. It will overwrite if newFileName exist
            sendCommand("RNTO " + newFileName);
            if (ReturnValue != 250)
            {
                throw new IOException(Reply.Substring(4));
            }
        }

        /// <summary>
        /// Create a directory on the remote FTP server.
        /// </summary>
        /// <param name="dirName">Name of the dir.</param>
        public void mkdir(string dirName)
        {
            isLogin();
            sendCommand("MKD " + dirName);
            if (ReturnValue != 250)
            {
                throw new IOException(Reply.Substring(4));
            }
        }

        /// <summary>
        /// Delete a directory on the remote FTP server.
        /// </summary>
        /// <param name="dirName">Name of the dir.</param>
        public void rmdir(string dirName)
        {
            isLogin();
            sendCommand("RMD " + dirName);
            if (ReturnValue != 250)
            {
                throw new IOException(Reply.Substring(4));
            }
        }

        /// <summary>
        /// Change the current working directory on the remote FTP server.
        /// </summary>
        /// <param name="dirName">Name of the dir.</param>
        public void chdir(string dirName)
        {
            if (dirName.Equals("."))
            {
                return;
            }
            isLogin();
            sendCommand("CWD " + dirName);
            if (ReturnValue != 250)
            {
                throw new IOException(Reply.Substring(4));
            }
            this.ThePath = dirName;
            Console.WriteLine("Current directory is " + ThePath);
        }

        /// <summary>
        /// Enters the passive mode.
        /// </summary>
        /// <author>spesme</author>
        /// <since>23/06/2009</since>
        public void enterPassiveMode()
        {
            sendCommand("PASV");
        }

        /// <summary>
        /// Opens a data port.
        /// </summary>
        /// <param name="p_dataPort">The dataport (192,168,1,20,15,61).</param>
        /// <author>spesme</author>
        /// <since>23/06/2009</since>
        public void openDataPort(string p_dataPort)
        {
            sendCommand("PORT" + SPACE + p_dataPort);
        }

        /// <summary>
        /// Retrieves the file from server.
        /// </summary>
        /// <param name="p_file">The file.</param>
        /// <author>spesme</author>
        /// <since>23/06/2009</since>
        public void retrieveFile(string p_file)
        {
            sendCommand("RETR" + SPACE + p_file);
        }

        /// <summary>
        /// Stores the file on the server.
        /// </summary>
        /// <param name="p_file">The p_file.</param>
        /// <author>spesme</author>
        /// <since>23/06/2009</since>
        public void storeFile(string p_file)
        {
            sendCommand("STOR" + SPACE + p_file);
        }

        /// <summary>
        /// Gets the data port (192,168,1,20,15,61).
        /// </summary>
        /// <returns></returns>
        /// <author>spesme</author>
        /// <since>23/06/2009</since>
        public string getDataPort()
        {
            String result = Reply;
            if (result != null && result.Contains(OPEN_BRACKET) && result.Contains(CLOSE_BRACKET))
            {
                int start = result.IndexOf(OPEN_BRACKET) + 1;
                int stop = result.IndexOf(CLOSE_BRACKET);
                result = result.Substring(start, stop - start);
            }
            return result;
        }

        /// <summary>
        /// Close the FTP connection.
        /// </summary>
        public void close()
        {
            if (clientSocket != null)
            {
                sendCommand("QUIT");
            }
            cleanup();
            Console.WriteLine("Closing...");
        }

        /// <summary>
        /// Sets the debug.
        /// </summary>
        /// <param name="debug">if set to <c>true</c> [debug].</param>
        public void setDebug(Boolean debug)
        {
            this.debug = debug;
        }

        private void readReply()
        {
            message = "";
            Reply = readLine();
            ReturnValue = Int32.Parse(Reply.Substring(0, 3));
        }

        private void cleanup()
        {
            if (clientSocket != null)
            {
                clientSocket.Close();
                clientSocket = null;
            }
            logined = false;
        }

        private string readLine()
        {
            while (true)
            {
                bytes = clientSocket.Receive(buffer, buffer.Length, 0);
                message += ASCII.GetString(buffer, 0, bytes);
                if (bytes < buffer.Length)
                {
                    break;
                }
            }
            char[] seperator = { '\n' };
            string[] mess = message.Split(seperator);
            if (message.Length > 2)
            {
                message = mess[mess.Length - 2];
            }
            else
            {
                message = mess[0];
            }
            if (!message.Substring(3, 1).Equals(" "))
            {
                return readLine();
            }
            if (debug)
            {
                for (int k = 0; k < mess.Length - 1; k++)
                {
                    Console.WriteLine(mess[k]);
                }
            }
            return message;
        }

        /// <summary>
        /// Sends a FTP command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <author>spesme</author>
        /// <since>26/06/2009</since>
        private void sendCommand(String command)
        {
            Byte[] cmdBytes = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray());
            clientSocket.Send(cmdBytes, cmdBytes.Length, 0);
            readReply();
        }

        /// <summary>
        /// Creates the data socket.
        /// </summary>
        /// <returns></returns>
        /// <author>spesme</author>
        /// <since>26/06/2009</since>
        private Socket createDataSocket()
        {
            sendCommand("PASV");
            if (ReturnValue != 227)
            {
                throw new IOException(Reply.Substring(4));
            }
            int index1 = Reply.IndexOf('(');
            int index2 = Reply.IndexOf(')');
            string ipData = Reply.Substring(index1 + 1, index2 - index1 - 1);
            int[] parts = new int[6];
            int len = ipData.Length;
            int partCount = 0;
            string buf = "";
            for (int i = 0; i < len && partCount <= 6; i++)
            {
                char ch = Char.Parse(ipData.Substring(i, 1));
                if (Char.IsDigit(ch))
                    buf += ch;
                else if (ch != ',')
                {
                    throw new IOException("Malformed PASV reply: " + Reply);
                }
                if (ch == ',' || i + 1 == len)
                {
                    try
                    {
                        parts[partCount++] = Int32.Parse(buf);
                        buf = "";
                    }
                    catch (Exception)
                    {
                        throw new IOException("Malformed PASV reply: " + Reply);
                    }
                }
            }
            string ipAddress = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];
            int port = (parts[4] << 8) + parts[5];
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ep = new IPEndPoint(Dns.Resolve(ipAddress).AddressList[0], port);
            try
            {
                socket.Connect(ep);
            }
            catch (Exception)
            {
                throw new IOException("Can't connect to remote server");
            }
            return socket;
        }

    }
}